/*
 * Created by guoyh on Mon Dec 26 2022 21:46:31
 * leetcode NO.328 https://leetcode.cn/problems/odd-even-linked-list/ 
 */
#include <iostream>
#include <gtest/gtest.h>
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        if(!head) return head;

        ListNode* odd = head;
        ListNode* even = head->next;
        ListNode* even_head = head->next;
        while(even && even->next){
            // 条件1: even != nullptr; 条件2: even->next
            odd->next = even->next;
            odd = odd->next;
            even->next = odd->next; // 条件1 保证even->next不会空指针,条件2 保证odd->next 不会空指针
            even = even->next;
        }
        odd->next = even_head;
        return head;
    }
};


// 尾插法创建链表
ListNode* build_linklist(vector<int> v){
    ListNode* dummy = new ListNode();
    ListNode* tail = dummy;
    for(int i : v){
        ListNode* newNode = new ListNode(i);
        newNode->next = nullptr;
        tail->next = newNode;
        tail = tail->next;
    }
    return dummy->next;
}

vector<int> linklist2vector(ListNode* l){
    vector<int> res;
    if(!l) return res;
    while(l){
        res.push_back(l->val);
        l = l->next;
    }
    return res;
}

void print(ListNode* l){
    while(l){
        cout<<l->val<<",";
        l = l->next;
    }
    cout<<endl;
}


int add(int a, int b) {
    return a + b;
}

TEST(MyTest, AddTest) {
    EXPECT_EQ(add(1, 2), 3);
}
TEST(MYTEST, Test01){
    vector<int> v1 = {2,1,3,5,6,4,7};
    ListNode* l1 = build_linklist(v1);
    Solution slu;
    ListNode* l2 = slu.oddEvenList(l1);
    vector<int> v2 = linklist2vector(l2);
    EXPECT_EQ(v2[0], 2);
    EXPECT_EQ(v2[1], 3);
    EXPECT_EQ(v2[2], 6);
    EXPECT_EQ(v2[6], 4);

}

int main(int argc, char *argv[]) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
